const fs = require('fs')
const nodeUtil = require('util');
const express = require('express')
const router = express.Router()
const util = require('../util')
const timer = require('../timer')
const config = require('../config')

const readdir = nodeUtil.promisify(fs.readdir);   //读取目录内容
const readFile = nodeUtil.promisify(fs.readFile);   //写文件

const logger = util.getLogger('routes.index')

/**
 * ip段,格式: { partition: {ips: [{ ip, status }], updatetime: ''} }
 */
let ipPartition = {}

/**
 * 解析扫描结果
 */
const analyzeResult = (result) => {
  if (! ipPartition[result.ip_prefix] || ipPartition[result.ip_prefix].updatetime < result.updatetime) {
    logger.info('load file : ' + result.ip_prefix)
    let ips = result.status.map(x => {
      return {
        ip: x[0],
        status: x[1]
      }
    })
    ipPartition[result.ip_prefix] = {
      ips, updatetime: result.updatetime
    }
  }
}

//文件扫描
config.ipScan === 'file' && timer.addTask({
  name: 'load ips by file',
  cycle: config.ipScanCycle,
  async fun () {
    try{
      let files = await readdir(config.ipStatusPath)
      logger.debug('加载ip扫描结果文件: ', files)
      for(let i in files) {
        let jsonStr = await readFile(`${config.ipStatusPath}/${files[i]}`, 'utf8')
        logger.debug(`${files[i]} -- `, jsonStr)
        let json = JSON.parse(jsonStr)
        logger.info(`更新时间 : ${json.updatetime}`)

        analyzeResult(json)
      }
    }catch(e){
      logger.error('读取ip扫描结果目录异常:', e)
    }
  }
})

//脚本扫描
config.ipScan === 'shell' && timer.addTask({
  name: 'load ips by shell',
  cycle: config.ipScanCycle,
  async fun () {
    try{
      logger.debug('scan ip:', config.ipPart)
      for (let i in config.ipPart) {
        let part = config.ipPart[i]
        let commond = `python /opt/install/scripts/ip-scan.py ${part} --json`
        let jsonStr = await util.runExec(commond)
        logger.debug('scan result:', jsonStr)
        let json = JSON.parse(jsonStr.stdout)
        logger.info(`更新时间 : ${json.updatetime}`)

        analyzeResult(json)
      }

    }catch(e){
      logger.error('shell error:', e)
    }
  }
})

/* GET home page. */
router.get('/', (req, res, next) => {
  res.send(util.sucResMsg)
})

router.get('/api/partition', (req, res) => {
  let parts = []
  for(let i in ipPartition){
    let status = ipPartition[i].ips.reduce((total, value) => {
      total[value.status] += 1
      return total
    }, {
      disable: 0,
      used: 0,
      available: 0
    })
    parts.push({
      part: i,
      status
    })
  }
  res.send(parts)
})

router.get('/api/partition/:part', (req, res) => {
  res.send(ipPartition[req.params.part])
})

module.exports = router;
